
package com.xtsoft.platform.base.system.service.impl;


import com.xtsoft.core.service.impl.GenericServiceImpl;
import com.xtsoft.core.utils.ResultMsg;
import com.xtsoft.platform.base.system.domain.*;
import com.xtsoft.platform.base.system.repository.ResourceRoleRepository;
import com.xtsoft.platform.base.system.repository.SysRoleRepository;
import com.xtsoft.platform.base.system.repository.SysUserRepository;
import com.xtsoft.platform.base.system.repository.UserRoleRepository;
import com.xtsoft.platform.base.system.service.SysUserService;
import com.xtsoft.platform.globe.Constants.Constants;
import com.xtsoft.platform.globe.enums.ResourceType;
import com.xtsoft.platform.globe.enums.YesNo;
import com.xtsoft.platform.globe.utils.EncryptUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;
@Service("sysUserService")
public class SysUserServiceImpl extends GenericServiceImpl<SysUser, String, SysUserRepository>
		implements SysUserService {

	@Autowired
	private SysUserRepository sysUserRepository;

	@Autowired
	private UserRoleRepository userRoleRepository;

	@Autowired
	private SysRoleRepository sysRoleRepository;



	@Autowired
	private ResourceRoleRepository resourceRoleRepository;
	
	
	@Override
	@Transactional
	public ResultMsg impower(String ids, String userId) {
		String[] roleIds = ids.split(",");
		Optional<SysUser> sysUser = sysUserRepository.findById(userId);
		if (!sysUser.isPresent()) {
			return new ResultMsg(false, "未知的对象授权");
		}
		// 删除用户拥有的角色
		userRoleRepository.deleteBySysUser(sysUser.get());
		// 获取角色集合
		List<SysRole> sysRoles = sysRoleRepository.findByRoleIdInAndState(Arrays.asList(roleIds),
				YesNo.Yes.getIntValue());
		List<UserRole> userRoles = new ArrayList();
		sysRoles.forEach(action -> {
			UserRole userRole = new UserRole();
			userRole.setSysUser(sysUser.get());
			userRole.setSysRole(action);
			userRoles.add(userRole);
		});
		
		userRoleRepository.saveAll(userRoles);
		return new ResultMsg(true, "用户授权成功");   
	}

	/**
	 * error ::: String[] arrId = userIds.split(",");   string   
	 */
	@Override
	@Transactional
	public ResultMsg enableOrDisable(String userIds) {
		String[] arrId = userIds.split(",");
		List<String> sysUserIds = Arrays.asList(arrId);
		sysUserRepository.setStateByUserIds(sysUserIds);
		return new ResultMsg(true, "用户状态更改成功");
	};

	@Override
	@Transactional
	public ResultMsg resetPassword(String userIds) {
		String[] arrId = userIds.split(",");
		List<String> sysUserIds = Arrays.asList(arrId);
		sysUserRepository.setPasswordByUserIds(EncryptUtil.passwordEncoder("bcrypt").encode(Constants.InitPassword), sysUserIds);
		return new ResultMsg(true, "用户密码重置成功,重置后的密码为：" + Constants.InitPassword);
	}

	/**
	 * 修改个人信息
	 */

	@Override
	@Transactional
	public SysUser saveUser(SysUser sysUser) {
		Optional<SysUser> user = sysUserRepository.findById(sysUser.getUserId());
		if (!user.isPresent()) {
			return null;
		}
		user.get().setFilePath(sysUser.getFilePath());
		user.get().setEmail(sysUser.getEmail());
		user.get().setPassword(sysUser.getPassword());
		user.get().setDescript(sysUser.getDescript());
		sysUserRepository.save(user.get());
		return user.get();		
		
	}

	@Override
	public SysUser findByLoginId(String loginId) {
		Optional<SysUser> optional = sysUserRepository.findByLoginId(loginId);
		if (!optional.isPresent()) {
			return null;
		}
		return sysUserRepository.findByLoginId(loginId).get();
	}


    public SysUser findByUserName(String userName) {
        return null;
    }


    /*
	 *(non-Javadoc)  
	*/
	@Override
	public List<SysRole> getSysRoles(String userId) {
		// TODO Auto-generated method stub
		Optional<SysUser> user = sysUserRepository.findById(userId);
		//找不到用户返回空
		if(!user.isPresent()) {
			//没有授权返回空
			return null;
		}
		List<UserRole> userRoles = userRoleRepository.findBySysUser(user.get());

		if(null == userRoles || userRoles.size() < 1) {
			return null;
		}

		return userRoles.stream()
				.map(mapper->mapper.getSysRole())
				.distinct()
				.collect(Collectors.toList());
	}

	/*  
	 *(non-Javadoc)  
	*/
	@Override
	public List<SysResource> getSysResources(String userId) {
		// TODO Auto-generated method stub
		List<SysRole> roles = getSysRoles(userId);
		if(null == roles || roles.size() < 1) {
			return null;
		}
		List<ResourceRole> resourceRoles = resourceRoleRepository.findBySysRoleIn(roles);
		if(null == resourceRoles || resourceRoles.size() < 1) {
			return null;
		}
		return resourceRoles.stream()
				.map(mapper->mapper.getSysResource())
				.distinct()
				.collect(Collectors.toList());
	}

	/*  
	 *(non-Javadoc)  
	*/
	@Override
	public List<SysResource> getButton(String userId, String preResourceId) {
		// TODO Auto-generated method stub
		List<SysResource> resources = getSysResources(userId);
		if(null == resources || resources.size() <1) {
			return null;
		}
		
		List<SysResource> result = resources.stream()
				.filter(predicate->predicate.getPreResourceId().equals(preResourceId) && predicate.getResourceType() == ResourceType.Button.getIntValue())
				.collect(Collectors.toList());
		
		Collections.sort(result,new Comparator<SysResource>() {
			@Override
			public int compare(SysResource o1, SysResource o2) {
				return o1.getSerialNo().compareTo(o2.getSerialNo());
			}
		
		});
		return result;
	}

	/*  
	 *(non-Javadoc)  
	*/
	@Override
	public String getButtonStr(String userId, String preResourceId) {
		// TODO Auto-generated method stub
		List<SysResource> resources = getButton(userId,preResourceId);
		if(null == resources || resources.size() < 1) {
			return  "[]";
		}
		
			
		StringBuffer buff = new StringBuffer("[");
		resources.forEach(action->buff.append("{id:'" + action.getResourceId() 
			+ "',name:'" + action.getResourceNick()
			+ "',icon:'" + action.getIconClsId()
			+ "',tooltip:'" + action.getToolTip()
			+ "',method:'" + action.getAttachMethod()
			+ "',color:'" + action.getButtonClr() 
			+ "'},"));

		return buff.substring(0, buff.length() - 1) + "]";
	}

	@Override
	public boolean isAdmin(SysUser sysUser,String role) {
		int count = sysUserRepository.checkAdmin(sysUser.getUserId(),role);
		return count==0?false:true;
	}






}